package com.mayjean.gateway.listener;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.nacos.api.config.ConfigType;
import com.alibaba.nacos.api.config.annotation.NacosConfigListener;
import com.mayjean.common.NezhaConstant;
import com.mayjean.common.util.SpringUtil;
import com.mayjean.gateway.props.NezhaGatewayProperties;
import com.mayjean.gateway.props.NezhaGatewayPropertiesConverter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionRepository;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * Dynamic router service
 *
 * @author
 */
@Slf4j
public class DynamicGatewayRouteDefinitionListener implements RouteDefinitionRepository {

	private List<RouteDefinition> routeDefinitions;
	/**
	 * update list
	 *
	 * @param routeDefinitions route definitions {@link List< RouteDefinition >}
	 */
	private void updateList(List<RouteDefinition> routeDefinitions) {
		if (routeDefinitions != null && routeDefinitions.size() > 0) {
			this.routeDefinitions = routeDefinitions;
			SpringUtil.publishEvent(new RefreshRoutesEvent(this));
		}
	}

	@Override
	public Flux<RouteDefinition> getRouteDefinitions() {
		if (this.routeDefinitions == null) {
			this.routeDefinitions = CollUtil.newArrayList();
		}
		return Flux.fromIterable(this.routeDefinitions);
	}

	@Override
	public Mono<Void> save(Mono<RouteDefinition> route) {
		return null;
	}

	@Override
	public Mono<Void> delete(Mono<String> routeId) {
		return null;
	}

	@NacosConfigListener(dataId = NezhaGatewayProperties.DATA_ID
			, groupId = NezhaGatewayProperties.GATEWAY_GROUP_ID
			, type = ConfigType.YAML, converter = NezhaGatewayPropertiesConverter.class
			, timeout = NezhaConstant.NACOS_LISTENER_DEFAULT_TIME_OUT)
	public void onChange(NezhaGatewayProperties nezhaGatewayProperties) {
		if (nezhaGatewayProperties != null && nezhaGatewayProperties.getRoutes().size() != 0) {
			this.updateList(nezhaGatewayProperties.getRoutes());
		}
	}
}
